package com.util.library.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.protocol.HTTP;

import com.util.library.common.ConfigLib;
import com.util.library.common.Utils;

import android.accounts.NetworkErrorException;
import android.net.ParseException;

public class OpenHttpConnection
{
	public InputStream get(String urlString) throws IOException,
			NetworkErrorException
	{
		InputStream inputStream = null;

		URL url = new URL(urlString);
		URLConnection connection = url.openConnection();

		if (!(connection instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
		try
		{
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			httpConnection.setAllowUserInteraction(false);
			httpConnection.setInstanceFollowRedirects(true);
			httpConnection.setRequestMethod("GET");
			httpConnection.connect();
			if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
			{
				inputStream = httpConnection.getInputStream();
			}
		} catch (Exception ex)
		{
			throw new IOException("Error connecting");
		}
		if (inputStream != null) Utils.debug("Get inputStream ok !!!");
		else throw new NetworkErrorException("Error connecting");
		return inputStream;
	}

	public String post(String baseUrlString, String dataString)
			throws IOException
	{
		// InputStream inputStream = null;
		String resultString = null;
		URL url = new URL(baseUrlString);
		HttpURLConnection httpURLConnection = null;
		try
		{
			httpURLConnection = (HttpURLConnection) url.openConnection();
			Utils.debug("1111");
			httpURLConnection.setDoOutput(true);
			Utils.debug("11112");
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			Utils.debug("11113");
			httpURLConnection.setRequestMethod("POST");
			Utils.debug("11114");
			httpURLConnection.setConnectTimeout(ConfigLib.NETWORKING_TIMEOUT);
			Utils.debug("111141");
			/* Error: timeout will stuck ? there no network */
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
			/* end error */

			Utils.debug("11115");
			outputStreamWriter.write(dataString);
			Utils.debug("11116");
			outputStreamWriter.flush();
			Utils.debug("11117");
			outputStreamWriter.close();
			Utils.debug("11118");
			// if (httpURLConnection.getResponseCode() ==
			// HttpURLConnection.HTTP_OK)
			// {
			// inputStream = httpURLConnection.getInputStream();
			// }
			// Utils.debug("11119");
			// if(inputStream == null)
			// {
			// Utils.debug("1111111118 get stream ok!");
			// throw new IOException("Error connecting");
			// }

			InputStreamReader streamReader;
			streamReader = new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8");
			// streamReader = new InputStreamReader(
			// httpURLConnection.getInputStream());
			Utils.debug("11119");
			StringBuilder builder = new StringBuilder();
			for (int bt = 0; (bt = streamReader.read()) != -1;)
			{
				builder.append((char) bt);
			}
			Utils.debug("111110");
			streamReader.close();
			Utils.debug("1111111111 get stream ok!");
			resultString = builder.toString();
		} catch (Exception ex)
		{
			throw new IOException("Error connecting");
		} finally
		{
			if (httpURLConnection != null)
			{
				httpURLConnection.disconnect();
			}
		}
		return resultString;
	}

	public String post(String baseUrlString) throws IOException
	{
		// InputStream inputStream = null;
		String resultString = null;
		URL url = new URL(baseUrlString);
		HttpURLConnection httpURLConnection = null;
		try
		{
			httpURLConnection = (HttpURLConnection) url.openConnection();
			Utils.debug("1111");
			httpURLConnection.setDoOutput(true);
			Utils.debug("11112");
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			Utils.debug("11113");
			httpURLConnection.setRequestMethod("POST");
			Utils.debug("11114");
			httpURLConnection.setConnectTimeout(ConfigLib.NETWORKING_TIMEOUT);
			Utils.debug("111141");
			/* Error: timeout will stuck ? there no network */
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
			/* end error */

			Utils.debug("11115");
			// outputStreamWriter.write(dataString);
			Utils.debug("11116");
			outputStreamWriter.flush();
			Utils.debug("11117");
			outputStreamWriter.close();
			Utils.debug("11118");
			// if (httpURLConnection.getResponseCode() ==
			// HttpURLConnection.HTTP_OK)
			// {
			// inputStream = httpURLConnection.getInputStream();
			// }
			// Utils.debug("11119");
			// if(inputStream == null)
			// {
			// Utils.debug("1111111118 get stream ok!");
			// throw new IOException("Error connecting");
			// }

			InputStreamReader streamReader;
			streamReader = new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8");
			// streamReader = new InputStreamReader(
			// httpURLConnection.getInputStream());
			Utils.debug("11119");
			StringBuilder builder = new StringBuilder();
			for (int bt = 0; (bt = streamReader.read()) != -1;)
			{
				builder.append((char) bt);
			}
			Utils.debug("111110");
			streamReader.close();
			Utils.debug("1111111111 get stream ok!");
			resultString = builder.toString();
		} catch (Exception ex)
		{
			throw new IOException("Error connecting");
		} finally
		{
			if (httpURLConnection != null)
			{
				httpURLConnection.disconnect();
			}
		}
		return resultString;
	}

	@SuppressWarnings("unused")
	private String replaceSpecialCharacters(String url)
	{
		String tempString = null;
		url = url.trim();
		if (url != null)
		{
			for (int i = 0; i < url.length(); i++)
			{
				char charAtI = url.charAt(i);
				if (charAtI == ' ') tempString += "%20";
				else if (charAtI == '@') tempString += "%40";
				else tempString += charAtI;
			}
		}
		return tempString;
	}

	public static String getResponseBody(HttpResponse response)
	{
		String response_text = null;
		HttpEntity entity = null;
		try
		{
			entity = response.getEntity();
			response_text = getResponseBody(entity);
		} catch (ParseException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
			if (entity != null)
			{
				try
				{
					entity.consumeContent();
				} catch (IOException e1)
				{
					e1.printStackTrace();
				}
			}
		}
		return response_text;
	}

	public static String getResponseBody(final HttpEntity entity)
			throws IOException, ParseException
	{
		if (entity == null)
		{
			throw new IllegalArgumentException("HTTP entity may not be null");
		}

		InputStream instream = entity.getContent();
		if (instream == null)
		{
			return "";
		}

		if (entity.getContentLength() > Integer.MAX_VALUE)
		{
			throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
		}

		String charset = getContentCharSet(entity);
		if (charset == null)
		{
			charset = HTTP.DEFAULT_CONTENT_CHARSET;
		}

		Reader reader = new InputStreamReader(instream, charset);
		StringBuilder buffer = new StringBuilder();

		try
		{
			char[] arrayChar = new char[1024];
			int len;
			while ((len = reader.read(arrayChar)) != -1)
			{
				buffer.append(arrayChar, 0, len);
			}
		} finally
		{
			reader.close();
		}

		return buffer.toString();
	}

	public static String getContentCharSet(final HttpEntity entity)
			throws ParseException
	{
		if (entity == null)
		{
			throw new IllegalArgumentException("HTTP entity may not be null");
		}

		String charset = null;
		if (entity.getContentType() != null)
		{
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0)
			{
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null)
				{
					charset = param.getValue();
				}
			}
		}

		return charset;
	}
}
